#!/usr/bin/env python
# Copyright 2006 James Bunton <james@delx.cjb.net> 
# Licensed for distribution under the GPL version 2, check COPYING for details

import unittest
import os.path, sys



class TestTwisted(unittest.TestCase):
	def twistedDir(self):
		return os.path.abspath(".") # Dummy entry to test system installed Twisted

	def setUp(self):
		sys.path.insert(1, self.twistedDir())
		twistfix = __import__("twistfix")
		twistfix.main()

	def tearDown(self):
		del sys.modules["twistfix"]
		for m in sys.modules.keys()[:]:
			if m.startswith("twisted") or m.startswith("twistfix"):
				del sys.modules[m]
		sys.path.remove(self.twistedDir())
	
	def testImports(self):
		try:
			from twisted.words.xish.domish import SuxElementStream, Element, unescapeFromXml
			from twisted.words.protocols.jabber import jid, component
			from twisted.web.http import HTTPClient
		except ImportError, e:
			self.fail("Failed to import: " + str(e))

	def testParserFunctions(self):
		from twisted.words.xish.domish import parseText, parseFile
		e = parseText("<tag attr='value'>body</tag>")
		self.assertEquals(e.name, "tag")
		self.assertEquals(e["attr"], "value")
		self.assertEquals(e.__str__(), "body")

		e = parseText("")
		self.assertEquals(e, None)
		e = parseText("0")
		self.assertEquals(e, None)
	
	def testInternJID(self):
		from twisted.words.protocols.jabber.jid import internJID
		f = lambda s: internJID(s).full()
		uh = lambda s: internJID(s).userhost()

		self.assertEquals(f("ME@ME.COM"), f("me@me.com"))
		self.assertNotEquals(f("me@me.com"), f("me2@me.com"))
		self.assertEquals(uh("me@me.com"), uh("me@me.com/resource"))
		self.assertNotEquals(f("me@me.com/R"), f("me@me.com/r"))
	
	def testElement(self):
		from twisted.words.xish.domish import Element
		e = Element((None, "tag"))
		e["attr"] = "value"
		e.addContent("body")
		self.assertEquals(e.toXml().replace("\n", ""), "<tag attr='value'>body</tag>")
	
	def testTwistdScripts(self):
		from twisted.scripts import _twistd_unix as twistd
		funcs = ("checkPID", "removePID", "daemonize")
		for f in funcs:
			self.assertTrue(hasattr(twistd, f))


class TestTwisted130(TestTwisted):
	def twistedDir(self):
		return os.path.abspath("releases/twisted-1.3.0")

class TestTwisted201(TestTwisted):
	def twistedDir(self):
		return os.path.abspath("releases/twisted-2.0.1")

class TestTwisted210(TestTwisted):
	def twistedDir(self):
		return os.path.abspath("releases/twisted-2.1.0")

class TestTwisted220(TestTwisted):
	def twistedDir(self):
		return os.path.abspath("releases/twisted-2.2.0")

class TestTwisted240(TestTwisted):
	def twistedDir(self):
		return os.path.abspath("releases/twisted-2.4.0")

class TestTwisted250(TestTwisted):
	def twistedDir(self):
		return os.path.abspath("releases/twisted-2.5.0")


if __name__ == "__main__":
	unittest.main()

